<script lang="ts" setup name="Service">
import { Check, CirclePlus, Close, EditPen, Refresh, User } from '@element-plus/icons-vue'
import { ProTableInstance } from '~/library/components/ProTable/interface'
import { StoreManagement } from '~/src/api/interface/storeManagement'
import {
  authorizationElementAPI,
  authorizationMeituanAPI,
  cancelServiceAPI,
  createActivationCodeAPI,
  createMerchantAPI,
  doSignCheckAPI,
  editMerchantAPI,
  editServiceAPI,
  getMerchantAPI,
  getServiceAPI,
  setServiceAPI,
} from '~/src/api/storeManagement'
import { resetPasswordAPI } from '~/src/api/user'
import { formatDate } from '~/src/utils/date-formatter'
import { downloadFile } from '~/src/utils/downLoad'
import ByGroupDialog from '../components/ByGroupDialog.vue'
import MerchantDialog from '../components/MerchantDialog.vue'
import ServiceDialog from '../components/ServiceDialog.vue'
import { serviceLeftColumns, serviceRightColumns } from './info/columns'
const leftProTable = ref<ProTableInstance>()
const rightProTable = ref<ProTableInstance>()
const initParam = ref({ groupId: 0 })

const dataCallback = (data: any) => {
  leftProTable.value!.element!.clearSelection()
  initParam.value.groupId = 0
  return {
    list: data.list,
    total: data.total,
    pageNum: data.pageNum,
    pageSize: data.pageSize,
  }
}

const onRadio = (row: StoreManagement.Service) => {
  if (initParam.value.groupId !== row.id) {
    initParam.value.groupId = row.id
  }
}
// 设置为服务商
const setRow = async (params: StoreManagement.Merchant) => {
  await useHandleData(setServiceAPI, { id: params.id }, `设置【${params.storeName}】为服务商`)
  leftProTable.value?.getTableList()
}

// 取消为服务商
const cancelRow = async (params: StoreManagement.Service) => {
  await useHandleData(cancelServiceAPI, { id: params.id }, `取消【${params.name}】为服务商`)
  leftProTable.value?.getTableList()
  rightProTable.value?.getTableList()
}

// 审核短信签名
const checkRow = async (message: string, params: StoreManagement.Merchant) => {
  await useHandleData(doSignCheckAPI, { id: params.id }, `${message}【${params.storeName}】短信签名`)
  rightProTable.value?.getTableList()
}

// 美团授权
const authorizationMeituan = async (id: number) => {
  const res = await authorizationMeituanAPI({ id })
  downloadFile(res.data as string, '', true)
}

// 饿了么授权
const authorizationElement = async (id: number) => {
  const res = await authorizationElementAPI({ id })
  downloadFile(res.data as string, '', true)
}
const resetPassword = async (params: StoreManagement.Merchant) => {
  await useHandleData(resetPasswordAPI, { id: params.id }, `重置【${params.storeName}】密码`)
}

const byGroupDialogRef = ref<InstanceType<typeof ByGroupDialog> | null>(null)
const openByGroupDialog = (title: string, row: Partial<StoreManagement.Merchant> = {}) => {
  const params = {
    title,
    data: { ...row },
    api: createMerchantAPI,
    getTableList: rightProTable.value?.getTableList,
  }
  byGroupDialogRef.value?.acceptParams(params)
}

const serviceDialogRef = ref<InstanceType<typeof ServiceDialog> | null>(null)
const openServiceDialog = (title: string, row: Partial<StoreManagement.Merchant> = {}) => {
  const params = {
    title,
    data: { ...row },
    api: editServiceAPI,
    getTableList: leftProTable.value?.getTableList,
  }
  serviceDialogRef.value?.acceptParams(params)
}

const merchantDialogRef = ref<InstanceType<typeof MerchantDialog> | null>(null)
const openMerchantDialog = (row: Partial<StoreManagement.Merchant> = {}) => {
  const params = {
    title: '商户资料',
    isView: false,
    data: { ...row },
    isService: true,
    api: editMerchantAPI,
    getTableList: rightProTable.value?.getTableList,
  }
  merchantDialogRef.value?.acceptParams(params)
}

const addGroup = () => {
  if (initParam.value.groupId !== 0) {
    openByGroupDialog('新增', {
      groupId: initParam.value.groupId,
      isCreateFacCode: true,
      passWord: '',
      createCount: 1,
      endDate: formatDate(366, 'start', 'yyyy-MM-dd'),
    })
  } else {
    ElMessage.error('请选中一个服务商')
  }
}
</script>

<template>
  <div class="auto-height-container">
    <div class="content">
      <div class="left-box">
        <pro-table
          ref="leftProTable"
          :columns="serviceLeftColumns"
          :data-callback="dataCallback"
          :request-api="getServiceAPI"
          :search-col="{ xs: 1, sm: 1, md: 1, lg: 2, xl: 2 }"
          title="服务商列表"
          @row-click="onRadio"
        >
          <!-- <template #tableHeader>
          <el-button type="primary" :icon="Setting" @click="openDialog('新增')"> 价格设置 </el-button>
        </template> -->
          <template #operation="scope">
            <el-button v-auth="'editStore'" :icon="EditPen" link type="primary" @click.stop="openServiceDialog('编辑', scope.row)">
              编辑
            </el-button>
            <el-button v-auth="'cancel'" :icon="Close" link type="primary" @click.stop="cancelRow(scope.row)">取消服务商</el-button>
          </template>
        </pro-table>
      </div>
      <div class="right-box ml8">
        <pro-table
          ref="rightProTable"
          :columns="serviceRightColumns"
          :init-param="initParam"
          :request-api="getMerchantAPI"
          :search-col="{ xs: 1, sm: 1, md: 2, lg: 3, xl: 3 }"
          title="商户列表"
        >
          <template #tableHeader>
            <el-button v-auth="'addStore'" :icon="CirclePlus" type="primary" @click="addGroup">新增商户</el-button>
          </template>
          <template #operation="scope">
            <el-dropdown trigger="hover">
              <el-button type="primary">
                操作菜单
                <el-icon><arrow-down /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item>
                    <el-button v-auth="'editStore'" :icon="EditPen" link type="primary" @click.stop="openMerchantDialog(scope.row)">
                      编辑
                    </el-button>
                  </el-dropdown-item>
                  <el-dropdown-item>
                    <el-button
                      v-if="scope.row.smsCheckFlag"
                      v-auth="'check'"
                      :icon="Check"
                      link
                      type="primary"
                      @click.stop="checkRow(scope.row.smsCheckFlag === 1 ? '审核' : '取消审核', scope.row)"
                    >
                      {{ scope.row.smsCheckFlag === 1 ? '审核签名' : '取消审核' }}
                    </el-button>
                  </el-dropdown-item>
                  <el-dropdown-item>
                    <el-button v-auth="'set'" :icon="Check" link type="primary" @click.stop="setRow(scope.row)">设为服务商</el-button>
                  </el-dropdown-item>
                  <el-dropdown-item>
                    <el-button v-auth="'reSet'" :icon="Refresh" link type="primary" @click="resetPassword(scope.row)">重置密码</el-button>
                  </el-dropdown-item>
                  <el-dropdown-item>
                    <el-button :icon="User" link type="primary" @click="authorizationMeituan(scope.row.id)">美团授权</el-button>
                  </el-dropdown-item>
                  <el-dropdown-item>
                    <el-button :icon="User" link type="primary" @click="authorizationElement(scope.row.id)">饿了么授权</el-button>
                  </el-dropdown-item>
                  <el-dropdown-item>
                    <el-button
                      :icon="User"
                      link
                      type="primary"
                      @click="
                        async () => {
                          await createActivationCodeAPI({ id: scope.row.id })
                          rightProTable?.getTableList()
                        }
                      "
                    >
                      创建激活码
                    </el-button>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </pro-table>
      </div>
    </div>
    <by-group-dialog ref="byGroupDialogRef" />
    <service-dialog ref="serviceDialogRef" />
    <merchant-dialog ref="merchantDialogRef" />
  </div>
</template>

<style lang="scss" scoped>
.content {
  display: flex;
  width: 100%;
  height: 100%;
  .left-box {
    display: flex;
    flex-direction: column;
    flex-shrink: 0;
    width: 470px;
    height: 100%;
  }
  .right-box {
    display: flex;
    flex: 1;
    flex-direction: column;
    width: calc(100% - 470px);
    height: 100%;
  }
}
</style>
